﻿Imports System.IO
Imports System.Text.Encoding
Imports System.Security.Cryptography
Imports System.Text
Imports System.Configuration

Friend Class Crypto

    Private Shared encryptionKey As String = "12345678"
    Private Shared IV() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF}

    Friend Shared Function Encrypt(ByVal stringToEncrypt As String) As String
        Try
            'Get encryption key from web.config.
            encryptionKey = GetConfigEncriptionKey()

            Dim des As New DESCryptoServiceProvider()
            Dim inputByteArray() As Byte = Encoding.UTF8.GetBytes(stringToEncrypt)
            Dim ms As New MemoryStream()
            Dim cs As New CryptoStream(ms, des.CreateEncryptor(System.Text.Encoding.UTF8.GetBytes(encryptionKey), IV), CryptoStreamMode.Write)

            cs.Write(inputByteArray, 0, inputByteArray.Length)
            cs.FlushFinalBlock()

            Return System.Convert.ToBase64String(ms.ToArray())
        Catch e As Exception
            Return stringToEncrypt
        End Try
    End Function

    Friend Shared Function Decrypt(ByVal stringToDecrypt As String) As String
        Try
            'Get encryption key from web.config.
            encryptionKey = GetConfigEncriptionKey()

            Dim des As New DESCryptoServiceProvider()
            Dim ms As New MemoryStream()
            Dim cs As New CryptoStream(ms, des.CreateDecryptor(System.Text.Encoding.UTF8.GetBytes(encryptionKey), IV), CryptoStreamMode.Write)
            Dim inputByteArray(stringToDecrypt.Length) As Byte
            Dim encoding As System.Text.Encoding = System.Text.Encoding.UTF8

            inputByteArray = System.Convert.FromBase64String(stringToDecrypt)
            cs.Write(inputByteArray, 0, inputByteArray.Length)
            cs.FlushFinalBlock()

            Return encoding.GetString(ms.ToArray())
        Catch e As Exception
            Return stringToDecrypt
        End Try
    End Function

    Private Shared Function GetConfigEncriptionKey()
        If ConfigurationManager.AppSettings("ManicEncryptionKey") IsNot Nothing Then
            Dim configEncriptionKey As String = ConfigurationManager.AppSettings("ManicEncryptionKey").Trim
            If configEncriptionKey.Length = 8 Then
                Return configEncriptionKey
            End If
        End If
        Return encryptionKey
    End Function

End Class